package com.hdoit.apollo.web.purchase.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.common.enums.stock.InStockState;
import com.hdoit.apollo.logical.common.enums.stock.InStockType;
import com.hdoit.apollo.logical.inStock.model.InStock;
import com.hdoit.apollo.logical.inStock.service.IInStockService;
import com.hdoit.apollo.logical.purchase.model.Purchase;
import com.hdoit.apollo.logical.purchase.service.IPurchaseService;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.stock.service.IOutStockService;
import com.hdoit.apollo.logical.viewmodel.stock.InStockSearch;
import com.tennetcn.authority.component.web.ActionResult;
import com.tennetcn.authority.component.web.BaseController;
import com.tennetcn.authority.component.web.ErrorResult;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;


@Controller
@RequestMapping(value = "/purchase/returnPurchase/")
public class ReturnPurchaseController extends BaseController{

	@Override
	public String getRoutePath() {
		
		 return "areas/purchase/returnPurchase/";
	}
	
	private final String indexViewName="index";
	private final String newIndexViewName="newIndex";
    private final String outputViewName="output";
    private final String detailedViewName="detailed";
    private final String newDetailedViewName="newDetailed";
    private final String selInStock = "selInStock";
    
    
    private final String seeDetailedViewName="seeDetailed";

    private final String deleteViewName = "delete";
    
    private final String closeViewName="close";
    
    
    private final String purchaseSelectViewName="purchaseSelect";
    
    private final String outStockPrintViewName = "outStockDetailPrint";
    
    private final String saveOutStockViewName="saveOutStock";
    
    @Autowired
    private IOutStockService outStockService;
    
    @Autowired
    private IInStockService inStockService;
    
    @Autowired
    private IPurchaseService purchaseService;
    
    
    @RequestMapping(value = newIndexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String newIndex(Model model,PagerModel pagerModel,InStockSearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(inStockService.queryCountMPForReturn(search));
        List<InStock> inStocks= inStockService.queryListMPForReturn(search,pagerModel);

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("inStocks", inStocks);
        model.addAttribute("inStockSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(newIndexViewName);
    }
    
	  @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
	    public String index(Model model,PagerModel pagerModel,InStockSearch search,boolean ajaxPost){

	        pagerModel.setTotalAmount(inStockService.queryCountMPForReturn(search));
	        List<InStock> inStocks= inStockService.queryListMPForReturn(search,pagerModel);

	        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
	        model.addAttribute("inStocks", inStocks);
	        model.addAttribute("inStockSearch", search);

	        if(ajaxPost){
	            return view(outputViewName);
	        }

	        return view(indexViewName);
	    }
	  
	  @RequestMapping(value = saveOutStockViewName, method = { RequestMethod.POST})
	    public String saveOutStock(Model model,InStock inStock,String ids){
	    	Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
	    	String [] numMark=inStock.getInStockNums().split(",");
	     	//String [] collocationIds=inStock.getCollocationIds().split(",");
	     	String [] prices=inStock.getInStockPrices().split(",");
	     	
	        if(StringUtils.isEmpty(inStock.getInStockId())){
	        	
	        	Double num=0.0;
	        	Double price=0.0;
	        	
	        	for (int i = 0; i < numMark.length; i++) {
					
	        		
	        		Double numberMark=Double.parseDouble(numMark[i]);
					Double priceMark=Double.parseDouble(prices[i])*numberMark;
					
					price=priceMark+price;
					num=numberMark+num;
				}
	        	inStock.setInStockNum(num);
	        	inStock.setReturnMoney(price);
	        	inStock.setInStockId(CommonUtils.getKeyId());
	        	inStock.setCreateDate(DateUtils.getCurrent());
	        	inStock.setDeleteMark(YesOrNoInteger.no);
	        	inStock.setCreateUserId(getLoginModel().getLoginId());
	        	inStock.setCreateUserName(getLoginModel().getLoginName());
	        	inStock.setShopId(shop.getShopId());
	        	inStock.setType(InStockType.outWarehouse);
	        	inStock.setInStockState(InStockState.finish);
	        	inStock.setModelStatus(ModelStatus.add);
	        }else{
	        	inStock.setModifyDate(DateUtils.getCurrent());
	        	inStock.setModifyUserId(getLoginModel().getLoginId());
	        	inStock.setModifyUserName(getLoginModel().getLoginName());
	        	inStock.setModelStatus(ModelStatus.update);
	        	System.err.println("wolaile");
	        }

	        ActionResult actionResult;
	        if(inStockService.applyInStockForPC(inStock,ids)){
	            actionResult=new ActionResult();
	        }else{
	            actionResult=new ErrorResult();
	        }

	        model.addAttribute("inStock", inStock);

	        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

	        return view(newDetailedViewName);
	    }
	  
	  @RequestMapping(value = newDetailedViewName, method = { RequestMethod.GET})
	    public String newDetailed(Model model,String key){
		  InStock inStock=new InStock();
	        if(!StringUtils.isEmpty(key)){
	        	inStock=inStockService.queryModel(key);
	        }
	        model.addAttribute("inStock", inStock);
	        return view(newDetailedViewName);
	    }
	  
	  @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
	    public String purchaseCollocationDetailed(Model model,String key){
		  InStock inStock=new InStock();
	        if(!StringUtils.isEmpty(key)){
	        	inStock=inStockService.queryModel(key);
	        }
	        model.addAttribute("inStock", inStock);
	        return view(detailedViewName);
	    }
	  

	  @RequestMapping(value = seeDetailedViewName, method = { RequestMethod.GET})
	    public String seeDetailed(Model model,String key){
		  InStock inStock=new InStock();
	        if(!StringUtils.isEmpty(key)){
	        	inStock=inStockService.queryModelBySee(key);
	        }
	        model.addAttribute("inStock", inStock);
	        model.addAttribute("inStockJson", JsonUtils.writeValueAsString(inStock));
	        return view(seeDetailedViewName);
	    }
	  
	  
	   
	    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
	    public @ResponseBody String delete(String key){
	        if(outStockService.deleteFakeByKey(key)){
	            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
	        }
	        return new JsonActionResult(ManageContainer.ERROR).toJson();
	    }
	    
	    
	    @RequestMapping(value = closeViewName, method = { RequestMethod.POST},produces = "text/html;charset=UTF-8")
	    public @ResponseBody String close(Model model,String key){
	    	InStock inStock=new InStock();
	        if(!StringUtils.isEmpty(key)){
	        	inStock=inStockService.queryModelById(key);
	        	inStock.setType(InStockType.close);
	        }
	    	if(!inStockService.closeInStock(inStock,getLoginModel().getLoginId(),getLoginModel().getLoginName())){
	    		return new JsonActionResult(ManageContainer.ERROR).toJson();
	    	}
			
			return new JsonActionResult(ManageContainer.SUCCESS).toJson();
	    }
	    
	    @RequestMapping(value = outStockPrintViewName, method = { RequestMethod.GET,RequestMethod.POST })
		public String outStockPrint(Model model, String key) {
			Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
			//Purchase purchase = new Purchase();
			InStock inStock=new InStock();

			if (!StringUtils.isEmpty(key)) {
				inStock = inStockService.queryModelBySee(key);	
			}
			
			if (inStock!=null) {			
				model.addAttribute("inStock", inStock);
			}
			model.addAttribute("shop", shop);
			return view(outStockPrintViewName);
		}
	    
	    @RequestMapping(value = purchaseSelectViewName, method = { RequestMethod.GET }, produces = "text/html;charset=UTF-8")
	   	public @ResponseBody String purchaseSelect(String purchaseId) {
	    	 Purchase purchase=new Purchase();
	    	
	    	 purchase=purchaseService.queryModelByKey(purchaseId);
	   		
	   		return JsonUtils.writeValueAsString(purchase);
	   	}
	    
	    @RequestMapping(value = selInStock, method = { RequestMethod.GET})
	    public String selInStock(Model model,String key){
	    	 InStock inStock=new InStock();
	        
	        if(!StringUtils.isEmpty(key)){
	        	inStock=inStockService.queryModelBySee(key);
	            
	        }
	        model.addAttribute("inStock", inStock);
	        return view(selInStock);
	    }
}
